﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using SuCasa.Infrastructure;

namespace SuCasa.DataAccess
{
    public interface ISessionRepository {
        List<Session> GetSessionsByCourse(Course course);
        bool AddCourse(Course course);
        List<Course> GetAll();
        Course GetCourseBy(Func<Course, bool> func);
        List<Session> GetSessionByCourseId(Course course);
        bool AddSession(Member member, Course course);
    }

    public class SessionRepository : ISessionRepository{
        readonly SuCasaDbContext _context;

        public SessionRepository(SuCasaDbContext context)
        {
            _context = context;
        }

        public List<Session> GetSessionsByCourse(Course course)
        {
            return _context.Sessions.Where(x => x.CourseId == course.CourseId).ToList();
        }

        public bool AddCourse(Course course)
        {
            if (course.CourseId == 0)
            {
                _context.Courses.Add(course);
            }
            else
            {
                _context.Courses.Attach(course);
                _context.Entry(course).State = EntityState.Modified;

            }
            return _context.SaveChanges() > 0;
        }

        public List<Course> GetAll()
        {
            return _context.Courses.ToList();
        }

        public Course GetCourseBy(Func<Course, bool> func)
        {
            return _context.Courses.SingleOrDefault(func);
        }

        public List<Session> GetSessionByCourseId(Course course)
        {
            return _context.Sessions.Where(x => x.CourseId == course.CourseId).ToList();
        }

        public bool AddSession(Member member, Course course)
        {
            Session session = new Session
            {
                CourseId = course.CourseId,
                StudentId = member.MemberId,
                Grade = 0,
                Homework = false,
                Attended = false,
                Timestamp = DateTime.Now
            };

            _context.Sessions.Add(session);

            return _context.SaveChanges() > 0;
        }
    }
}
